<template>
  <div>
    <myTable :list="list">
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #body="obj">
        <td>{{ obj.obj.id }}</td>
        <td>{{ obj.obj.goods_name }}</td>
        <td>{{ obj.obj.goods_price }}</td>
        <td>
          <button
            class="btn btn-primary btn-sm add-tag"
            v-if="!obj.obj.inputVisible"
            @click="obj.obj.inputVisible = true"
          >
            +Tag
          </button>
          <input
            type="text"
            v-else
            class="tag-input form-control"
            v-focus
            @blur="blurFn(obj.obj)"
            @keyup.enter="enterFn(obj.obj, $event.target.value)"
            @keyup.esc="$event.target.value = ''"
          />
          <span
            v-for="(item, index) in obj.obj.tags"
            :key="index"
            class="badge badge-warning"
            >{{ item }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="del(obj.delIndex)">
            删除
          </button>
        </td>
      </template>
    </myTable>
  </div>
</template>

<script>
import myTable from "../components/MyTable";
export default {
  directives: {
    focus: {
      inserted(el) {
        el.focus();
      },
    },
  },
  methods: {
    enterFn(obj, val) {
      if (val) {
        obj.tags.push(val);
        obj.inputVisible = false;
        return;
      }
      this.flag = 1;
      alert("输入不能为空");
    },
    blurFn(obj) {
      if (!this.flag) {
        obj.inputVisible = false;
        return;
      }
      this.flag = 0;
    },
    del(index) {
      this.list.splice(index, 1);
    },
  },
  data() {
    return {
      list: [],
      flag: 0,
    };
  },
  created() {
    this.$axios({
      url: "/api/goods",
    }).then((res) => (this.list = res.data.data));
  },
  components: {
    myTable,
  },
};
</script>

<style lang="less" scoped>
.badge {
  margin-left: 5px;
}
</style>